package com.lemon.smartsafety.ui.activity.safe.data;

import android.app.Activity;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.LinearLayoutManager;
import android.text.InputType;
import android.view.View;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.ldzs.recyclerlibrary.Mode;
import com.ldzs.recyclerlibrary.PullToRefreshRecyclerView;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppManager;
import com.lemon.smartsafety.app.AppService;
import com.lemon.smartsafety.app.BundleKey;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.app.EventTag;
import com.lemon.smartsafety.app.IApplication;
import com.lemon.smartsafety.app.RefreshType;
import com.lemon.smartsafety.entity.common.SelectDataI;
import com.lemon.smartsafety.entity.event.datacoll.BuildingGroupDeleteEvent;
import com.lemon.smartsafety.entity.event.datacoll.BuildingGroupRefreshEvent;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafety.http.service.SafeDataServices;
import com.lemon.smartsafety.listener.RecyclerTClickListener;
import com.lemon.smartsafetynew.ui.activity.base.SwipeBackActivity;
import com.lemon.smartsafety.ui.adapter.safe.data.BuildingGroupAdapter;
import com.lemon.smartsafety.utils.app.HUDUtil;
import com.lemon.smartsafety.utils.common.StringUtils;
import com.lemon.smartsafety.view.list.MultiStateView;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by Cooliean on 16/4/6.
 */
public class BuildingGroupManagerActivity extends SwipeBackActivity implements RecyclerTClickListener<SelectDataI> {

    @Bind(R.id.pullToRefreshRecyclerView)
    PullToRefreshRecyclerView mPullToRefreshRecyclerView;
    @Bind(R.id.multiStateView)
    MultiStateView            mMultiStateView;
    @Bind(R.id.float_button)
    FloatingActionButton      floatButton;
    private String mCompanyCode = "";


    public List<SelectDataI> mDataList = new ArrayList<>();

    private BuildingGroupAdapter mAdapter = null;


    @Override
    protected void initTitle() {
        setBarTitle("分组管理");
    }

    @Override
    protected void callFinish() {
        AppManager.getAppManager().finishActivity(BuildingGroupManagerActivity.class);
    }

    @Override
    protected void getBundleArgs() {
        super.getBundleArgs();
        if (getIntent().getExtras() != null) {
            mCompanyCode = getIntent().getStringExtra(BundleKey.COMPANY_CODE);
        }
        mCompanyCode = StringUtils.nullValue(mCompanyCode);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_list_refresh;
    }


    @Override
    protected void initViews() {
        super.initViews();
        floatButton.setVisibility(View.VISIBLE);
        mMultiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
        initRecyclerView();
    }


    private void initRecyclerView() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(IApplication.context(), LinearLayoutManager.VERTICAL, false);
        mPullToRefreshRecyclerView.setRefreshMode(Mode.PULL_FROM_START);
        mPullToRefreshRecyclerView.setLayoutManager(layoutManager);

        mAdapter = new BuildingGroupAdapter(mDataList, this);

        mPullToRefreshRecyclerView.setAdapter(mAdapter);
        mPullToRefreshRecyclerView.setOnPullUpToRefreshListener(new PullToRefreshRecyclerView.OnPullUpToRefreshListener() {
            @Override
            public void onRefresh() {
                getNetData();
            }
        });
        initMultiStateView();

        mPullToRefreshRecyclerView.beginRefreshing();
    }

    private void getNetData() {
        SafeDataServices.init().getBuildingGroupList(RefreshType.REFRESH, 1000, 1, "");
    }


    /**
     * http处理请求的处理
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(HttpCallbackEvent event) {
        if (EventTag.BUILDING_GROUP_LIST.equals(event.getTag())) {
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
                mHUDUtil.showHUD();
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                mHUDUtil.hidden();
                mPullToRefreshRecyclerView.onRefreshComplete();
                if (event.getEventResult() == Constants.Result.SUCCESS) {
                    httpRefresh((List) event.getObj());
                } else {
                    mMultiStateView.setErrorTip(event.getMsg());
                }
            }
        } else if (EventTag.TAG_BUILDING_GROUP_ACTION.equals(event.getTag())) {
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
                mHUDUtil.showHUD();
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                if (event.getEventResult() == Constants.Result.SUCCESS) {
                    mHUDUtil.showDoneTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {
                            mPullToRefreshRecyclerView.beginRefreshing();
                            BuildingGroupRefreshEvent refreshEvent = new BuildingGroupRefreshEvent();
                            AppService.getBus().post(refreshEvent);
                        }
                    });
                } else {
                    mHUDUtil.showErrorTip(event.getMsg());
                }
            }
        } else if (EventTag.TAG_BUILDING_GROUP_DELETE_ACTION.equals(event.getTag())) {
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
                mHUDUtil.showHUD();
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                if (event.getEventResult() == Constants.Result.SUCCESS) {
                    mHUDUtil.showDoneTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {
                            mPullToRefreshRecyclerView.beginRefreshing();
                            BuildingGroupRefreshEvent refreshEvent = new BuildingGroupRefreshEvent();
                            AppService.getBus().post(refreshEvent);
                        }
                    });
                } else {
                    mHUDUtil.showErrorTip(event.getMsg());
                }
            }
        }
    }

    @Subscribe
    public void onEventMainThread(final BuildingGroupDeleteEvent event) {
        if (StringUtils.nullValue(event.getData().getValue()).length() == 0) {
            mHUDUtil.showErrorTip(getString(R.string.params_error));
            return;
        }

        getConfirmDialog("是否删除（" + event.getData().getTitle() + "）?", new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                if (which == DialogAction.POSITIVE) {
                    SafeDataServices.init().deleteBuildingGroup(event.getData().getValue());
                }
            }
        }).show();
    }

    public void httpRefresh(List data) {
        if (data != null && !data.isEmpty()) {
            data.remove(data.size() - 1);
            mMultiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
            mPullToRefreshRecyclerView.setRefreshMode(Mode.PULL_FROM_START);
            mDataList.clear();
            mDataList.addAll(data);
            mAdapter.notifyDataSetChanged();
        } else {
            mMultiStateView.setEmptyTip("没有分组信息");
        }
    }

    private void initMultiStateView() {
        mMultiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
        mMultiStateView.setRetryListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mMultiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                mPullToRefreshRecyclerView.beginRefreshing();
            }
        });
    }


    @OnClick(R.id.float_button)
    public void floatButtonClick() {
        showAddDialog(this, mHUDUtil, mCompanyCode,"","");
    }


/*    public static void showAddDialog(final Activity activity, final HUDUtil hudUtil, final String mCompanyCode) {
        if (mCompanyCode.length() == 0) {
            hudUtil.showErrorTip(activity.getString(R.string.params_error));
            return;
        }
        new MaterialDialog.Builder(activity).title("新建分组")
                                            .content("请填写分组名称")
                                            .inputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_WORDS)
                                            .positiveText(R.string.submit_str)
                                            .inputRange(2, 20)
                                            .input("必填", "", false, new MaterialDialog.InputCallback() {
                                                @Override
                                                public void onInput(@NonNull MaterialDialog dialog, final CharSequence input) {
                                                    if (null != input && input.toString().length() != 0) {
                                                        showAddDialog(activity, hudUtil, mCompanyCode, "", "");
                                                    }
                                                }
                                            })
                                            .show();
    }*/


    public static void showAddDialog(Activity activity, HUDUtil hudUtil, final String mCompanyCode, final String groupId, String defaultValue) {
        if (mCompanyCode.length() == 0) {
            hudUtil.showErrorTip(activity.getString(R.string.params_error));
            return;
        }
        try {
            new MaterialDialog.Builder(activity).title("新建分组")
                                                .content("请填写分组名称")
                                                .inputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_WORDS)
                                                .positiveText(R.string.submit_str)
                                                .inputRange(2, 20)
                                                .input("必填", defaultValue, false, new MaterialDialog.InputCallback() {
                                                    @Override
                                                    public void onInput(@NonNull MaterialDialog dialog, final CharSequence input) {
                                                        if (null != input && input.toString().length() != 0) {
                                                            if (StringUtils.nullValue(groupId).length() != 0) {
                                                                SafeDataServices.init()
                                                                                .updateBuildingGroup(mCompanyCode, groupId, input
                                                                                        .toString());
                                                            }else{
                                                                SafeDataServices.init()
                                                                                .newBuildingGroup(mCompanyCode, input.toString());
                                                            }

                                                        }
                                                    }
                                                })
                                                .show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onItemClick(SelectDataI data, int position) {
        showAddDialog(this, mHUDUtil, mCompanyCode, data.getValue(), data.getTitle());
    }
}
